package com.lcz.fruitweb.web;


import com.lcz.fruitweb.service.FruitService;
import com.lcz.fruitweb.service.impl.FruitServiceImpl;
import com.lcz.fruitweb.util.JdbcUtil;
import lombok.SneakyThrows;
import model.Fruit;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author 才智
 */
@WebServlet("/fruitEdit")
public class FruitEditServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String strId = req.getParameter("id");
        int id = Integer.parseInt(strId);
        ApplicationContext applicationContext =(ApplicationContext) getServletContext().getAttribute("applicationContext");
        FruitService fruitService = applicationContext.getBean("fruitService",FruitService.class);
        Fruit fruit=fruitService.findFruitById(id);
        req.setAttribute("fruit",fruit);
        //无错
        req.getRequestDispatcher("fruitEdit.jsp").forward(req,resp);
    }
//        更新数据
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Fruit fruit = new Fruit();
        BeanUtils.populate(fruit, req.getParameterMap());

        ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");
        FruitService fruitService = applicationContext.getBean("fruitService",FruitService.class);
        boolean ret = fruitService.updateFruit(fruit);
            if (ret){
                resp.sendRedirect("fruitList");
            }else {
                req.getRequestDispatcher("fruitList.jsp").forward(req,resp);
            }
    }

}
